<?php
namespace app\common\model;

use think\Cache;
use think\Db;
use think\Model;

/*
 * 文件类
 * */

class File extends Model
{
    private function get_key($id){
        $key='cache_file_'.$id;
        return $key;
    }
    /*
     * @param $obj 文件对象
    */
    public function saveFile($obj=''){
        $file_info=$obj->getInfo();
        $data['md5']=$obj->md5();
        $data['sha1']=$obj->sha1();
        $data['type']=$obj->getExtension();
        $data['size']=$file_info['size'];
        $data['savename']=$obj->getFilename();
        $data['savepath']=str_replace('public','',config('upload_path').DS.$obj->getSaveName());
        $data['ctime']=time();
        $row=$this->where(array('md5'=>$data['md5']))->find();
        if($row){
            $file=ROOT_PATH.config('upload_path').DS.$obj->getSaveName();
            if(file_exists($file)){
                unlink($file);
            }
            return $row['id'];
        }
        if($this->insert($data)){
            return  $this->getLastInsID();
        }else{
            return false;
        }
    }
    /*  获取文件路径
     *  @param $id 文件id
     * */
    public function getImg($id){
        $cache_key=$this->get_key($id);
        $res=Cache::get($cache_key);
        if(!$res){
            $row=$this->where(array('id'=>$id))->find();
            if(!$row){
                return false;
            }
            $res=$row['savepath'];
            Cache::set($cache_key,$res);
        }
        return $res;
    }
}